from __future__ import division

from io.files import open_path
from util.workstreams import DataTable


class manage(object):
    def _size(self, item):
        compressed = []
        sz = 0

        p = open_path(item.file_path())
        if p.is_directory():
            for d in p.list_names().leaves().files():
                if d.is_link():
                    continue
                ext = d.path().extension()
                is_compressed = ext is not None and ext.lower() == 'gz'
                compressed.append(is_compressed)
                sz += d.size()

        if len(compressed) == 0:
            compress_ratio = 'N/A'
        else:
            compress_ratio = len(filter(lambda x: x, compressed)) / len(compressed)

        return sz, compress_ratio

    def _report(self, values):
        d = DataTable('workstream', 'size', 'compressed')
        x = sorted(values, lambda x, y: -cmp(x[1], y[1]))
        for item in x:
            d.add(*item)

        if len(d) > 0:
            t = d.table()
            t.set_format(1, t.ABBREVIATE)
            print t

    def __init__(self, wsdir):
        values = []
        for item in wsdir.streams():
            values.append((item,) + self._size(item))

        self._report(filter(lambda x: x[2] != 1, values))
        self._report(filter(lambda x: 0 < x[2] < 1, values))


if __name__ == '__main__':
    from easyconfig import Config
    c = Config()

    with c.parser() as p:
        pass

    with c.fetcher() as f:
        manage(c.workstreams())
